package com.wwc.controller;

import com.wwc.config.lb.LoadBalancer;
import com.wwc.entities.CommonResult;
import com.wwc.entities.Payment;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
@RequestMapping("/consumer/payment")
@Slf4j
@Api(value = "OrderController")
public class OrderController{
	// public static final String PAYMENT_URL = "http://localhost:8001/payment";
	public static final String PAYMENT_URL = "http://PAYMENT-SERVICE/payment";
	@Resource
	private RestTemplate restTemplate;
	@Resource
	private DiscoveryClient discoveryClient;
	@Resource
	private LoadBalancer loadBalancer;
	
	@GetMapping("/createPayment")
	@ApiOperation(value = "新增Payment数据")
	public CommonResult createPayment(Payment payment){
		return restTemplate.postForObject(PAYMENT_URL + "/createPayment", payment, CommonResult.class);
	}
	
	@GetMapping("/getPaymentByIdForObject/{id}")
	@ApiOperation(value = "根据id获取Payment数据,ForObject")
	public CommonResult getPaymentByIdForObject(@PathVariable("id") Long id){
		return restTemplate.getForObject(PAYMENT_URL + "/getPaymentById/" + id, CommonResult.class);
	}
	
	@GetMapping("/getPaymentByIdForEntity/{id}")
	@ApiOperation(value = "根据id获取Payment数据,ForEntity")
	public CommonResult getPaymentByIdForEntity(@PathVariable("id") Long id){
		ResponseEntity<CommonResult> responseEntity = restTemplate.getForEntity(PAYMENT_URL + "/getPaymentById/" + id, CommonResult.class);
		log.info("getPaymentByIdForEntity->responseEntity:{{}}", responseEntity);
		return responseEntity.getBody();
	}
	
	@GetMapping("/getDiscovery")
	@ApiOperation(value = "获取服务信息")
	public CommonResult getDiscovery(){
		return restTemplate.getForObject(PAYMENT_URL + "/getDiscovery", CommonResult.class);
	}
	
	@GetMapping("/getLoadBalanced")
	@ApiOperation(value = "随机算法，获取LoadBalanced端口")
	public String getLoadBalanced(){
		List<ServiceInstance> instances = discoveryClient.getInstances("PAYMENT-SERVICE");
		log.info("getLoadBalanced->instances:{{}}", instances);
		if(instances != null && !instances.isEmpty()){
			ServiceInstance serviceInstance = loadBalancer.instanceList(instances);
			URI uri = serviceInstance.getUri();
			log.info("getLoadBalanced->uri:{{}}", uri);
			return restTemplate.getForObject(uri + "/payment/getLoadBalanced", String.class);
		}
		return null;
	}
	
}
